package cn.edu.zafu.bigdata.x.zhouyuyan.work10;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class TCPServer {
    public static void main(String[] args) {
        int port = 12345;
        try(ServerSocket serverSocket = new ServerSocket(port)){
            System.out.println("服务端已启动，等待客户端连接...");

            while (true){
                try (Socket clientSocket = serverSocket.accept();
                     BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                     PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),true)){
                    System.out.println("客户端已连接：" + clientSocket.getInetAddress().getHostAddress());
                    String inputLine;
                    while ((inputLine = in.readLine()) != null){
                        System.out.println("收到客户端消息：" + inputLine);
                        out.println("服务端回复：" + inputLine);
                    }
                }catch (IOException e){
                    System.err.println("与客户端通信时出错：" + e.getMessage());
                }
            }
        }catch (IOException e){
            System.err.println("服务端启动失败：" + e.getMessage());
        }
    }
}
